<template>
  <el-dialog
    :model-value="open"
    :title="title"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <el-tabs v-model="activeNames" @tab-click="handleClick">
      <el-tab-pane label="基础数据" name="first">
        <el-row v-if="!isAdd">
          <el-col :span="1.5" class="top-right-btn">
            <el-button
              :loading="subBtn"
              type="primary"
              @click="submitForm"
            >
              保存
            </el-button>
          </el-col>
        </el-row>
        <el-form
          ref="editForm"
          inline
          :rules="rules"
          :model="form"
          label-width="150px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="服务商" prop="serviceProviderId" :label-position="labelPosition">
                <el-select
                  v-model="form.serviceProviderId"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.服务商]"
                    :key="dict.providerServiceCode"
                    :label="dict.serviceSimpleName"
                    :value="dict.providerServiceCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="channelChName" :label-position="labelPosition">
                <el-input v-model="form.channelChName" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="英文名称" prop="channelEnName" :label-position="labelPosition">
                <el-input v-model="form.channelEnName" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :label-position="labelPosition">
              <el-form-item label="产品分类" prop="productType">
                <el-select
                  v-model="form.productType"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.产品类别]"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品组" prop="productGroup" :label-position="labelPosition">
                <el-select
                  v-model="form.productGroup"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.产品组]"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收款币种" prop="collectionCurrency" :label-position="labelPosition">
                <el-select
                  v-model="form.collectionCurrency"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.收款币种]"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="后线客服员" prop="customerService" :label-position="labelPosition">
                <el-input v-model="form.customerService" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="燃油种类" prop="fuelTypeId" :label-position="labelPosition">
                <el-select
                  v-model="form.fuelTypeId"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.燃油种类]"
                    :key="dict.id"
                    :label="dict.fuelTypeChinese"
                    :value="dict.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计重规则" prop="weightRule" :label-position="labelPosition">
                <el-select
                  v-model="form.weightRule"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.计重规则]"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="材积系数" prop="volumeCoefficient" :label-position="labelPosition">
                <el-input-number
                  v-model="form.volumeCoefficient"
                  :controls="false"
                  clearable
                  style="width: 100%;"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="体积系数" prop="volumeFactor" :label-position="labelPosition">
                <el-input-number
                  v-model="form.volumeFactor"
                  :controls="false"
                  clearable
                  style="width: 100%;"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="打印代码" prop="printCode" :label-position="labelPosition">
                <el-select
                  v-model="form.printCode"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="dict in dicts[DictDirection.打印服务]"
                    :key="dict.printCode"
                    :label="dict.printCode"
                    :value="dict.printCode"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="交货地" prop="placeDelivery" :label-position="labelPosition">
                <el-input v-model="form.placeDelivery" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票代码" prop="invoiceCode" :label-position="labelPosition">
                <el-input v-model="form.invoiceCode" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态" prop="status" :label-position="labelPosition">
                <el-radio-group v-model="form.status" clearable>
                  <el-radio v-for="dict in dicts[DictDirection.通用状态]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark" :label-position="labelPosition">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  :rows="2"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item>
                <el-upload
                  ref="upload"
                  :disabled="isUploading"
                  action="#"
                  :limit="10"
                  :on-change="handleChangeFile"
                  :on-remove="handleRemoveFile"
                  :auto-upload="false"
                  :file-list="showFileList"
                  style="width: 700px;"
                >
                  <el-button
                    type="primary"
                    :disabled="isUploading"
                  >
                    选取发票模板
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="!isAdd" label="发货人信息" name="second">
        <shipperInformation v-if="productId!=null" :father-open="open" :product-id="productId" />
      </el-tab-pane>
      <el-tab-pane v-if="!isAdd" label="尺寸限制" name="third">
        <sizeLimit
          v-if="productId!=null"
          :father-open="open"
          :product-id="productId"
        />
      </el-tab-pane>
      <el-tab-pane v-if="!isAdd" label="费用管理" name="forth">
        <costManagement v-if="productId!=null" :father-open="open" :product-id="productId" />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <div>
        <el-button
          v-if="isAdd"
          type="primary"
          @click="submitForm"
        >
          确定
        </el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  ref,
  getCurrentInstance,
  defineExpose,
  defineEmits,
  defineAsyncComponent,
  watch,
} from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import {
  addData,
  editData,
  getDetails,
} from '@/api/BusinessConfig/serviceChannel'

const shipperInformation = defineAsyncComponent(() => import('./shipperInformation.vue'))
const sizeLimit = defineAsyncComponent(() => import('./sizeLimit.vue'))
const costManagement = defineAsyncComponent(() => import('./costManagement.vue'))
const dicts = useDicts()
dicts.setDicts(DictDirection.计重规则)
dicts.setDicts(DictDirection.产品类别)
dicts.setDicts(DictDirection.通用状态)
dicts.setDicts(DictDirection.产品状态)
dicts.setDicts(DictDirection.产品组)
dicts.setDicts(DictDirection.服务商)
dicts.setDicts(DictDirection.燃油种类)
dicts.setDicts(DictDirection.打印服务)
dicts.setDicts(DictDirection.收款币种)
const props = defineProps({
  open: {
    type: Boolean,
  },
  title: {
    type: String,
    default: '',
  },
  isAdd: {
    type: Boolean,
  },
})

const emit = defineEmits(['changeList', 'update:title', 'update:isAdd', 'update:open'])
const labelPosition = ref('right')
const // 模态框显示
  channelOpen = ref(false),
  // 切换栏
  activeNames = ref('first'),
  // 基础数据加载
  subBtn = ref(false),
  // 标题
  title = ref(''),
  isUploading = ref(false)
const // 新增-修改表单
  form = ref({
    id: undefined,
    salesProductCode: undefined,
    salesProductName: undefined,
    serviceProviderId: undefined,
    channelChName: undefined,
    channelEnName: undefined,
    productType: undefined,
    productGroup: undefined,
    collectionCurrency: undefined,
    customerService: undefined,
    fuelTypeId: undefined,
    weightRule: undefined,
    woodWeight: undefined,
    volumeCoefficient: undefined,
    volumeFactor: undefined,
    printCode: undefined,
    placeDelivery: undefined,
    invoiceCode: undefined,
    status: 1,
    remark: undefined,
    invoice: undefined,
    invoiceFile: [],
  }),
  // 规则
  rules = {
    fuelTypeId: [{ required: true, message: '服务商代码未输入', trigger: 'blur' }],
    serviceProviderId: [{ required: true, message: '服务商代码未输入', trigger: 'blur' }],
    serviceChannelCode: [{ required: true, message: '服务渠道代码未输入', trigger: 'blur' }],
    channelChName: [{ required: true, message: '中文名称未输入', trigger: 'blur' }],
    channelEnName: [{ required: true, message: '英文名称未输入', trigger: 'blur' }],
    status: [{ required: true, message: '未选择状态', trigger: 'blur' }],
    productType: [
      {
        required: true,
        message: '未选择产品分类',
        trigger: ['blur', 'change'],
      },
    ],
    productGroup: [
      {
        required: true,
        message: '未选择产品组',
        trigger: ['blur', 'change'],
      },
    ],
    collectionCurrency: [
      {
        required: true,
        message: '未选择收款币种',
        trigger: ['blur', 'change'],
      },
    ],
    volumeCoefficient: [{ required: true, message: '材积系数未输入', trigger: 'blur' }],
    volumeFactor: [{ required: true, message: '体积系数未输入', trigger: 'blur' }],
    printCode: [
      {
        required: true,
        message: '打印代码未输入',
        trigger: ['blur', 'change'],
      },
    ],
  },
  // 新增修改表单
  editForm = ref(null),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()

let fileListOne = [],
  // 文件列表
  showFileList = ref<UploadUserFile[]>([
  ])
watch(fileListOne, (val) => {
  if (proxy.$refs.form) {
    if (val.length) {
      proxy.$refs.form.rules.printCode[0].required = false
    } else {
      proxy.$refs.form.rules.printCode[0].required = true
    }
  } 
})
watch(showFileList, (val) => {
  if (proxy.$refs.form) {
    if (val.length) {
      proxy.$refs.form.rules.printCode[0].required = false
    } else {
      proxy.$refs.form.rules.printCode[0].required = true
    }
  } 
})
// 重置表单
const reset = () => {
  form.value = {
    id: undefined,
    salesProductCode: undefined,
    salesProductName: undefined,
    serviceProviderId: undefined,
    channelChName: undefined,
    channelEnName: undefined,
    productType: undefined,
    productGroup: undefined,
    collectionCurrency: undefined,
    customerService: undefined,
    fuelTypeId: undefined,
    weightRule: undefined,
    woodWeight: undefined,
    volumeCoefficient: undefined,
    volumeFactor: undefined,
    printCode: undefined,
    placeDelivery: undefined,
    invoiceCode: undefined,
    status: 1,
    remark: undefined,
    invoice: undefined,
    invoiceFile: [],
  }
  proxy.$resetForm(editForm.value)
}
// 切换tab栏
const handleClick = (row: { [key: string]: any }) => {
  activeNames.value = row.paneName
}
// 文件状态改变,添加文件，上传成功，上传失败都会调用
const handleChangeFile = (file, fileList) => {
  fileListOne = fileList
}
const handleRemoveFile = (file, uploadFiles) => {
  showFileList.value = uploadFiles
  form.value.invoiceFile = uploadFiles.map(el => el.url)
}
// 确定新增-修改
const submitForm = () => {
  proxy.$validateForm(editForm.value, async () => {
    isUploading.value = true
    const serviceChannel = JSON.stringify(form.value)
    // eslint-disable-next-line prefer-const
    let data = new FormData()
    fileListOne.forEach(el => {
      if (el.status === 'ready') {
        data.append('files', el.raw)
      }
    })
    data.append('serviceChannel', serviceChannel)
    if (form.value.id != undefined) {
      editData(data).then(res => {
        if (res.code === 200) {
          isUploading.value = false
          reset()
          ElMessage.success('修改成功')
          fileListOne = []
          showFileList.value = []
          emit('update:isAdd', false)
          emit('update:open', false)
          emit('changeList')
        }
      })
    } else {
      addData(data).then(res => {
        if (res.code == 200) {
          isUploading.value = false
          reset()
          ElMessage.success('新增成功')
          fileListOne = []
          showFileList.value = []
          emit('update:isAdd', false)
          emit('update:open', false)
          emit('changeList')
        }
      })
    }
  })
}
// eslint-disable-next-line prefer-const
let productId = ref(null)
// 根据id查询修改的数据
const getList = (id) => {
  showFileList.value = []
  isUploading.value = false
  getDetails(id).then((res) => {
    form.value = res.data
    productId.value = form.value.id
    if (form.value.invoiceFile && form.value.invoiceFile.length) {
      form.value.invoiceFile = form.value.invoiceFile.map(el => {
        const result = { url: undefined, name: undefined }
        // const url = decodeURI(el)
        result.url = el
        const arr = el.split('/')
        result.name = arr[arr.length - 1]
        showFileList.value.push(result)
        form.value.invoiceFile.push(el)
        return el
      })
    }
  })
}
// 取消
const cancel = () => {
  activeNames.value = 'first'
  reset()
  fileListOne = []
  showFileList.value = []
  emit('update:open', false)
  emit('update:isAdd', false)
}
const handleClose = () => {
  reset()
  fileListOne = []
  showFileList.value = []
  emit('update:isAdd', false)
  emit('update:open', false)
}

defineExpose({
  channelOpen,
  getList,
})
</script>
<style lang="less">
.top-right-btn {
  margin: 20px 600px;
}
</style>
